import csv
import io
from typing import Optional

from app.database.enums import ServerPrivacy, ServerType
from app.database.models import AllowedIP, Order, Proxy, Server


def export_proxies_to_csv(
    order: Order,
    proxies: list[Proxy],
    server: Server,
    allowed_ip: Optional[AllowedIP] = None,
) -> bytes:
    output = io.StringIO()
    csv_writer = csv.writer(
        output,
        delimiter="\t",
        quotechar='"',
        quoting=csv.QUOTE_ALL,
        lineterminator="\r\n",
    )
    csv_writer.writerow(
        [
            "ip",
            "port_https",
            "login",
            "password",
            "reload_type",
            "reload_period",
            "authorization_type",
            "expiring_on",
            "authorization_ip",
            "reload_link",
        ]
    )
    for proxy in proxies:
        row = [
            server.ip_address,
            proxy.port_https,
        ]

        if proxy.authorization_type == "by_password":
            row.extend([proxy.login, proxy.password])
        else:
            row.extend(["", ""])

        row.extend(
            [
                proxy.reload_type,
                proxy.reload_period,
                proxy.authorization_type,
                order.expiring_on,
            ]
        )

        if allowed_ip:
            row.append(allowed_ip.ip_address)
        else:
            row.append("")
        if (
            server.proxy_privacy == ServerPrivacy.private
            and server.proxy_type == ServerType.mobile
            and proxy.reload_link
        ):
            row.append(f"http://{server.ip_address}/{proxy.reload_link}.php")

        csv_writer.writerow(row)

    return output.getvalue().encode("utf-16")
